package com.pda.yuanjing.pages.custombill.scanf;

import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.JieDianBeanIn;
import com.pda.yuanjing.beanin.ScanfBeanIn;
import com.pda.yuanjing.beanout.BaseBeanOut;
import com.pda.yuanjing.beanout.FMBeanOut;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.beanout.JDListBeanOut;
import com.pda.yuanjing.beanout.NoBillBeanOut;
import com.pda.yuanjing.beanout.PCBeanOut;
import com.pda.yuanjing.beanout.SCBeanOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.dialog.dealer.DealertDialog;
import com.pda.yuanjing.dialog.error.ErrorDialog;
import com.pda.yuanjing.dialog.fm.FMDialog;
import com.pda.yuanjing.dialog.hm.HMDialog;
import com.pda.yuanjing.dialog.kv.KVDialog;
import com.pda.yuanjing.dialog.product.ProductAllDialog;
import com.pda.yuanjing.dialog.product.ProducttDialog;
import com.pda.yuanjing.dialog.store.StoretDialog;
import com.pda.yuanjing.dialog.subcode.SubCodeDialog;
import com.pda.yuanjing.message.MessageBus;
import com.pda.yuanjing.thread.CodeBeans;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.dialogs.ChooseDialog;
import com.public_module.tools.DateUtils;
import com.public_module.tools.DensityUtil;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.VoiceUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ScanfActivity extends BaseActivity<ScanfModel, ScanfView, ScanfPresent> implements ScanfView {
    @BindView(R.id.lls)
    LinearLayout lls;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvzs)
    TextView tvzs;
    @BindView(R.id.ivs)
    ImageView ivs;
    @BindView(R.id.tvc1)
    TextView tvc1;
    @BindView(R.id.vline)
    View vline;
    @BindView(R.id.tvzsv)
    TextView tvzsv;
    @BindView(R.id.tvbatchNo)
    TextView tvbatchNo;
    @BindView(R.id.tvbatchNov)
    TextView tvbatchNov;
    @BindView(R.id.tvcd)
    TextView tvcd;
    @BindView(R.id.login_id)
    EditText loginId;
    @BindView(R.id.logine)
    Button logine;
    @BindView(R.id.ivd)
    ImageView ivd;
    @BindView(R.id.tvjc)
    TextView tvjc;
    @BindView(R.id.etres)
    TextView etres;
    @BindView(R.id.tvres)
    TextView tvres;
    @BindView(R.id.tvs)
    TextView tvs;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.tvwait)
    TextView tvwait;
    @BindView(R.id.dh)
    EditText dh;
    @BindView(R.id.tv000)
    TextView tv000;
    @BindView(R.id.tvdht)
    TextView tvdht;
    @BindView(R.id.tvtmt)
    TextView tvtmt;
    @BindView(R.id.tvstore)
    TextView tvstore;
    @BindView(R.id.tvstorev)
    TextView tvstorev;
    @BindView(R.id.rlk)
    RelativeLayout rlk;
    @BindView(R.id.tvpro)
    TextView tvpro;
    @BindView(R.id.tvprov)
    TextView tvprov;
    @BindView(R.id.rlp)
    RelativeLayout rlp;
    @BindView(R.id.tv00)
    TextView tv00;
    @BindView(R.id.etreason)
    EditText etreason;
    @BindView(R.id.tvms)
    TextView tvms;
    @BindView(R.id.llms)
    LinearLayout llms;
    @BindView(R.id.tvlc)
    TextView tvlc;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.tvjd)
    TextView tvjd;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.tvkf)
    TextView tvkf;
    @BindView(R.id.ll3)
    LinearLayout ll3;
    @BindView(R.id.tvgys)
    TextView tvgys;
    @BindView(R.id.ll4)
    LinearLayout ll4;
    @BindView(R.id.tvjxs)
    TextView tvjxs;
    @BindView(R.id.ll5)
    LinearLayout ll5;
    @BindView(R.id.tvr)
    TextView tvr;
    @BindView(R.id.tvde)
    TextView tvde;
    @BindView(R.id.tvdev)
    TextView tvdev;
    @BindView(R.id.rld)
    RelativeLayout rld;
    @BindView(R.id.cb)
    CheckBox cb;

    @BindView(R.id.rlst1)
    RelativeLayout rlst1;
    @BindView(R.id.rlst2)
    RelativeLayout rlst2;
    @BindView(R.id.rlst3)
    RelativeLayout rlst3;
    @BindView(R.id.tvxz1)
    TextView tvxz1;
    @BindView(R.id.tvxz2)
    TextView tvxz2;
    @BindView(R.id.dh1)
    EditText dh1;

    String tvxz1v="";
    String tvxz2v="";
    private String TAG = "ScanfActivity";
    private OptionsPickerView pickerView;
    int scanfState = 0;
    boolean flag = true;
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    VoiceUtils voiceUtils;
    JDBeanNewOut.DataBean dataBean = null;
    List<JDBeanNewOut.DataBean.ListSelectBean> tlist = new ArrayList<>();
    String key = "";
    List<Integer> codeNums = new ArrayList<>();
    int index = 0;
    CodeBeans codeBeans = new CodeBeans();
    int waitNum = 0;
    Thread upThread = null;
    boolean exit = false;
    CodeAdapter codeAdapter;
    List<NoBillBeanOut.DataBean.CodeInfoBean> plist = new ArrayList<>();
    String sid = "-1";
    String pid = "-1";
    String did = "-1";
    ProducttDialog productDialog;
    StoretDialog storeDialog;
    DealertDialog dealerDialog;
    SubCodeDialog subCodeDialog;
    ErrorDialog errorDialog;
    HMDialog hmDialog;
    FMDialog fmDialog;
    int total = 0;
    String pCode = "";
    String tempCode = "";
    boolean isFuMa = false;
    String zm = "";
    KVDialog kvDialog1;
    KVDialog kvDialog2;

    protected void initdata() {
        PDApp.scanffm = false;
        dataBean = (JDBeanNewOut.DataBean) getIntent().getSerializableExtra(PDApp.process);
        isFuMa = dataBean.isFuMa();
        if(isFuMa){
            cb.setVisibility(View.VISIBLE);
            if(dataBean.isFuMaNeedScan()){
                cb.setChecked(true);
                cb.setEnabled(false);
            }else{
                cb.setChecked(false);
                cb.setEnabled(true);
            }
        }else{
            cb.setVisibility(View.GONE);
        }
        if(dataBean.getListTSPZSelect1().size()>0){
            rlst1.setVisibility(View.VISIBLE);
            tvxz1.setText(dataBean.getTSPZSelectName1());
        }
        if(dataBean.getListTSPZSelect2().size()>0){
            rlst2.setVisibility(View.VISIBLE);
            tvxz2.setText(dataBean.getTSPZSelectName2());
        }
        if(dataBean.getIsNeedTXBeiZhu()){
            rlst3.setVisibility(View.VISIBLE);
            dh1.setHint(dataBean.getTXBeiZhuName());
        }

        tvTitle.setText(dataBean.getJieDianName() + " " + SharedPreferencesManger.getRealName());
        dh.setText(DateUtils.stampToDateTime(new Date().getTime()));
        tvzs.setText(dataBean.getJieBeiZhu());
        Glide.with(mContext).load(dataBean.getJieImage()).into(ivs);
        tvwait.setText(waitNum + "");
        presenter.initBase(dataBean.getProcessID(), dataBean.getJieDianName());
        codeNums = dataBean.getListCodeNums();
        if (dataBean.getRuKu()) {
            rlk.setVisibility(View.VISIBLE);
        }
        if (dataBean.getComfireProduct()) {
            rlp.setVisibility(View.VISIBLE);
        }
        if (dataBean.getComfireDealer()) {
            rld.setVisibility(View.VISIBLE);
        }
        tlist = dataBean.getListSelect();
        if (tlist != null && tlist.size() > 0) {
            lls.setVisibility(View.VISIBLE);
            tvjc.setVisibility(View.VISIBLE);
            etres.setVisibility(View.VISIBLE);
            llms.setVisibility(View.VISIBLE);
            pickerView = new OptionsPickerBuilder(ScanfActivity.this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    etres.setText(tlist.get(options1).getPickerViewText());
//                    key = tlist.get(options1).getPickerViewId();
                    key = tlist.get(options1).getPickerViewText();
                }
            })
                    .setTitleText("选择检测结果")
                    .setContentTextSize(20)//设置滚轮文字大小
                    .setTitleSize(20)
                    .setSubCalSize(20)
                    .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                    .setSelectOptions(0)//默认选中项
                    .setBgColor(Color.WHITE)
                    .setTitleBgColor(getResources().getColor(R.color.white))
                    .setTitleColor(getResources().getColor(R.color.black))
                    .setCancelColor(getResources().getColor(R.color.gray_high))
                    .setSubmitColor(getResources().getColor(R.color.blue))
                    .setTextColorCenter(getResources().getColor(R.color.black))
                    .setSubmitText("确定")
                    .setCancelText("取消")
                    .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                    .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                    .setOutSideColor(0x2A2A2A4F) //设置外部遮罩颜色
                    .build();
            pickerView.setPicker(tlist);
        }


        chooseDialog = new ChooseDialog(this, "是否开启删除条码", R.style.CommentDialog, new ChooseDialog.PriorityListener() {
            @Override
            public void setActivityText() {
                chooseDialog.dismiss();
                flag = false;
                ivd.setImageResource(R.mipmap.icon_check);
            }
        });
        WindowManager.LayoutParams lp = chooseDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;

        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                        tvs.setText(dataa.getStr());
                        scanfState = dataa.getType();
                        if (scanfState == -1) {
                            tvs.setBackgroundResource(R.color.smalltext);
                        } else {
                            tvs.setBackgroundResource(R.color.green);
                        }
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        String ss = StringProcess.codeMat(string);
                        if (!PDApp.scanf) {
                            return;
                        }
                        if (!PDApp.scanfp) {
                            getRes("1", ss);
                            return;
                        }
                        if (!PDApp.scanfs) {
                            getRes("2", ss);
                            return;
                        }
                        if (!PDApp.scanfsc) {
                            getSub(ss);
                            return;
                        }
                        if (!PDApp.scanfhm) {
                            hmDialog.setText(ss);
                            hm(tempCode, ss);
                            return;
                        }
                        if (isFuMa && cb.isChecked()) {
                            if (!PDApp.scanffm ) {
                                fmDialog = null;
                                fmDialog = new FMDialog(mContext, R.style.CommentDialog);
                                WindowManager.LayoutParams lpf = fmDialog.getWindow().getAttributes();
                                lpf.gravity = Gravity.CENTER;
                                fmDialog.show();
                                Window window = fmDialog.getWindow();
                                window.setBackgroundDrawableResource(android.R.color.transparent);
                                WindowManager.LayoutParams attrs = window.getAttributes();
                                attrs.width = (int) DensityUtil.dp2px(ScanfActivity.this, 300);
                                attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                                fmDialog.getWindow().setAttributes(attrs);
                                fmDialog.setZM(ss);
                                fm(ss);
                                zm = ss;
                            } else {
                                fmscanf(zm, ss);
                            }
                            return;
                        }
                        if(dataBean.getListTSPZSelect1().size()>0 && tvxz1v.equals("")){
                            showres("请选择特殊配置项1");
                            return;
                        }
                        if(dataBean.getListTSPZSelect2().size()>0 && tvxz2v.equals("")){
                            showres("请选择特殊配置项2");
                            return;
                        }
                        if (scanfState == -1) {
                            showres("网络异常,请检查网络");
                            return;
                        }
                        if (dh.getText().toString().length() == 0) {
                            showres("请填写单号");
                            return;
                        }
                        if (key.equals("") && tlist.size() > 0) {
                            showres("请填写质检结果");
                            return;
                        }
                        if (dataBean.getRuKu() && sid.equals("-1")) {
                            showres("请选择库房");
                            return;
                        }
                        if (dataBean.getComfireProduct() && pid.equals("-1")) {
                            showres("请选择产品");
                            return;
                        }
                        if (dataBean.getComfireDealer() && did.equals("-1")) {
                            showres("请选择经销商");
                            return;
                        }
                        CodeBeans.Code cbean = new CodeBeans.Code();
                        cbean.setStr(ss);
                        cbean.setFlag(flag);
                        codeBeans.addCode(cbean);
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
        upThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!exit) {
                    if (codeBeans != null && codeBeans.getCodes().size() > 0) {
                        try {
                            tempCode = codeBeans.getCodes().get(0).getStr();
                            presenter.scanfCodeNobill(dh.getText().toString(), dataBean.getProcessID(), dataBean.getJieDianName(), codeBeans.getCodes().get(0).getStr(), key, etreason.getText().toString(),
                                    sid, pid, did, codeBeans,tvxz1v,tvxz2v,dh1.getText().toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        upThread.start();
        codeAdapter = new CodeAdapter(this, plist);
        listview.setAdapter(codeAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control_scanf);
        ButterKnife.bind(this);
        initdata();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
        EventBus.getDefault().unregister(this);
        exit = true;
        upThread = null;
    }

    @Override
    public ScanfModel createModel() {
        return new ScanfModelImpl(this);
    }

    @Override
    public ScanfView createView() {
        return this;
    }

    @Override
    public ScanfPresent createPresenter() {
        return new ScanfPresent();
    }


    @OnClick({R.id.iv_title_left, R.id.logine, R.id.etres, R.id.ivd, R.id.tvstorev, R.id.tvprov, R.id.tvdev,R.id.rlst1,R.id.rlst2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tvstorev:
                storeDialog = new StoretDialog(mContext, R.style.CommentDialog, new StoretDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1) {
                        tvstorev.setText(str);
                        sid = str1;
                        storeDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp = storeDialog.getWindow().getAttributes();
                lp.gravity = Gravity.CENTER;
                storeDialog.show();
                break;
            case R.id.tvprov:
                productDialog = new ProducttDialog(mContext, R.style.CommentDialog, new ProducttDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1, int num) {
                        tvprov.setText(str);
                        pid = str1;
                        productDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp1 = productDialog.getWindow().getAttributes();
                lp1.gravity = Gravity.CENTER;
                productDialog.show();
                break;
            case R.id.tvdev:
                dealerDialog = new DealertDialog(mContext, R.style.CommentDialog, new DealertDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1) {
                        tvdev.setText(str);
                        did = str1;
                        dealerDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp2 = dealerDialog.getWindow().getAttributes();
                lp2.gravity = Gravity.CENTER;
                dealerDialog.show();
                break;
            case R.id.ivd:
                if (flag) {
                    chooseDialog.show();
                } else {
                    flag = true;
                    ivd.setImageResource(R.mipmap.icon_nocheck);
                }
                break;
            case R.id.logine:
                if (scanfState == -1) {
                    showres("网络异常,请检查网络");
                    return;
                }
                if (dh.getText().toString().length() == 0) {
                    showres("请填写单号");
                    return;
                }
                if (key.equals("") && tlist.size() > 0) {
                    showres("请填写质检结果");
                    return;
                }
                if (dataBean.getRuKu() && sid.equals("-1")) {
                    showres("请选择库房");
                    return;
                }
                if (dataBean.getComfireProduct() && pid.equals("-1")) {
                    showres("请选择产品");
                    return;
                }
                if (dataBean.getComfireDealer() && did.equals("-1")) {
                    showres("请选择经销商");
                    return;
                }
                if (isFuMa && cb.isChecked()) {
                    if (!PDApp.scanffm ) {
                        fmDialog = null;
                        fmDialog = new FMDialog(mContext, R.style.CommentDialog);
                        WindowManager.LayoutParams lpf = fmDialog.getWindow().getAttributes();
                        lpf.gravity = Gravity.CENTER;
                        fmDialog.show();
                        Window window = fmDialog.getWindow();
                        window.setBackgroundDrawableResource(android.R.color.transparent);
                        WindowManager.LayoutParams attrs = window.getAttributes();
                        attrs.width = (int) DensityUtil.dp2px(ScanfActivity.this, 300);
                        attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        fmDialog.getWindow().setAttributes(attrs);
                        fmDialog.setZM(loginId.getText().toString());
                        zm = loginId.getText().toString();
                        fm(loginId.getText().toString());
                    }
                    return;
                }
                CodeBeans.Code cbean = new CodeBeans.Code();
                cbean.setStr(loginId.getText().toString());
                cbean.setFlag(flag);
                codeBeans.addCode(cbean);
                break;
            case R.id.etres:
                pickerView.show();
                break;
            case R.id.rlst1:
                kvDialog1 = new KVDialog(mContext, R.style.CommentDialog, new KVDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1) {
                        tvxz1.setText(str);
                        tvxz1v = str1;
                    }
                },dataBean.getListTSPZSelect1());
                WindowManager.LayoutParams lp11 = kvDialog1.getWindow().getAttributes();
                lp11.gravity = Gravity.CENTER;
                kvDialog1.show();
                break;
            case R.id.rlst2:
                kvDialog2 = new KVDialog(mContext, R.style.CommentDialog, new KVDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1) {
                        tvxz2.setText(str);
                        tvxz2v = str1;
                    }
                },dataBean.getListTSPZSelect2());
                WindowManager.LayoutParams lp22 = kvDialog2.getWindow().getAttributes();
                lp22.gravity = Gravity.CENTER;
                kvDialog2.show();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void showres(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                voiceUtils.voiceWarn();
                tvres.setText(str);
                loginId.setText("");
                tvwait.setText(codeBeans.getCodes().size() + "");
                plist.clear();
                codeAdapter.notifyDataSetChanged();
                if (PDApp.cidInfoBeanOut.getData() != null && PDApp.cidInfoBeanOut.getData().isShowErrorDialog()) {
                    errorDialog = new ErrorDialog(mContext, str, R.style.CommentDialog, new ErrorDialog.PriorityListener() {
                        @Override
                        public void setActivityText() {
                        }
                    });
                    WindowManager.LayoutParams lp = errorDialog.getWindow().getAttributes();
                    lp.gravity = Gravity.CENTER;
                    errorDialog.show();
                    Window window = errorDialog.getWindow();
                    window.setBackgroundDrawableResource(android.R.color.transparent);
                    WindowManager.LayoutParams attrs = window.getAttributes();
                    attrs.width = (int) DensityUtil.dp2px(ScanfActivity.this, 300);
                    attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                    errorDialog.getWindow().setAttributes(attrs);
                }
            }
        });
    }

    @Override
    public void showSuccessres(JDListBeanOut jdListBeanOut) {

    }

    @Override
    public void onshowSuccessresNoBill(NoBillBeanOut.DataBean codeInfo) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (codeInfo != null && codeInfo.getCode() == 0) {
                    tvres.setText("数码处理完成");
                    loginId.setText("");
                    tvwait.setText(codeBeans.getCodes().size() + "");
                    total++;
                    tv000.setText(total + "");
                    if (codeInfo != null) {
                        plist.clear();
                        plist.add(codeInfo.getCodeInfo());
                        codeAdapter.notifyDataSetChanged();
                    }
                    if (dataBean.getHuanMa()) {
                        hmDialog = new HMDialog(mContext, R.style.CommentDialog, new HMDialog.PriorityListener() {
                            @Override
                            public void setActivityText() {
                            }
                        });
                        WindowManager.LayoutParams lp = hmDialog.getWindow().getAttributes();
                        lp.gravity = Gravity.CENTER;
                        hmDialog.show();
                        Window window = hmDialog.getWindow();
                        window.setBackgroundDrawableResource(android.R.color.transparent);
                        WindowManager.LayoutParams attrs = window.getAttributes();
                        attrs.width = (int) DensityUtil.dp2px(ScanfActivity.this, 300);
                        attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        hmDialog.getWindow().setAttributes(attrs);
                    }
                    if (codeInfo.getBomResult() != null && codeInfo.getBomResult().getIsNeedSubCode()) {
                        pCode = codeInfo.getCodeInfo().getListResult().get(0).getValue();
                        subCodeDialog = new SubCodeDialog(mContext, R.style.CommentDialog, codeInfo.getBomResult().getBomList(), new SubCodeDialog.PriorityListener() {
                            @Override
                            public void setActivityText() {
                            }
                        });
                        WindowManager.LayoutParams lp = subCodeDialog.getWindow().getAttributes();
                        lp.gravity = Gravity.CENTER;
                        subCodeDialog.show();
                        Window window = subCodeDialog.getWindow();
                        window.setBackgroundDrawableResource(android.R.color.transparent);
                        WindowManager.LayoutParams attrs = window.getAttributes();
                        attrs.width = (int) DensityUtil.dp2px(ScanfActivity.this, 300);
                        attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        subCodeDialog.getWindow().setAttributes(attrs);
                    }
                } else {
                    voiceUtils.voiceWarn();
                    if (codeInfo != null && codeInfo.getStr() != null) {
                        tvres.setText(codeInfo.getStr());
                    } else {
                        tvres.setText("数据处理异常");
                    }
                    loginId.setText("");
                    tvwait.setText(codeBeans.getCodes().size() + "");
                    if (codeInfo != null) {
                        plist.clear();
                        plist.add(codeInfo.getCodeInfo());
                        codeAdapter.notifyDataSetChanged();
                    }
                    if (PDApp.cidInfoBeanOut.getData() != null && PDApp.cidInfoBeanOut.getData().isShowErrorDialog()) {
                        errorDialog = new ErrorDialog(mContext, codeInfo.getStr(), R.style.CommentDialog, new ErrorDialog.PriorityListener() {
                            @Override
                            public void setActivityText() {
                            }
                        });
                        WindowManager.LayoutParams lp = errorDialog.getWindow().getAttributes();
                        lp.gravity = Gravity.CENTER;
                        errorDialog.show();
                        Window window = errorDialog.getWindow();
                        window.setBackgroundDrawableResource(android.R.color.transparent);
                        WindowManager.LayoutParams attrs = window.getAttributes();
                        attrs.width = (int) DensityUtil.dp2px(ScanfActivity.this, 315);
                        attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        errorDialog.getWindow().setAttributes(attrs);
                    }
                }
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(MessageBus messageBus) {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(String messageBus) {
        fmscanf(zm, messageBus);
    }

    public void getRes(String id, String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_QueryProdcutStoreByCode");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setBaseType(id);
            jieDianBeanIn.setCodecc(code);
            jieDianBeanIn.setProcessID(Integer.parseInt(pid));

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            SCBeanOut scBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), SCBeanOut.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (id.equals("1")) {
                                        productDialog.dismiss();
                                        if (scBeanOut.getData().getIdStr().equals("-1")) {
                                            showMsg("未匹配到产品信息");
                                        } else {
                                            boolean flag = true;
                                            for (int i = 0; i < PDApp.productBeanOutt.getData().size(); i++) {
                                                if (PDApp.productBeanOutt.getData().get(i).getId().equals(scBeanOut.getData().getIdStr())) {
                                                    flag = false;
                                                    break;
                                                }
                                            }
                                            if (flag) {
                                                showMsg("未匹配到产品信息");
                                                return;
                                            }
                                            tvprov.setText(scBeanOut.getData().getNameStr());
                                            pid = scBeanOut.getData().getIdStr();
                                        }
                                    } else if (id.equals("2")) {
                                        storeDialog.dismiss();
                                        if (scBeanOut.getData().getIdStr().equals("-1")) {
                                            showMsg("未匹配到库房信息");
                                        } else {
                                            boolean flag = true;
                                            for (int i = 0; i < PDApp.storeBeanOutt.getData().size(); i++) {
                                                if (PDApp.storeBeanOutt.getData().get(i).getId().equals(scBeanOut.getData().getIdStr())) {
                                                    flag = false;
                                                    break;
                                                }
                                            }
                                            if (flag) {
                                                showMsg("未匹配到库房信息");
                                                return;
                                            }
                                            tvstorev.setText(scBeanOut.getData().getNameStr());
                                            sid = scBeanOut.getData().getIdStr();
                                        }
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }


    public void getSub(String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_UpdateCode_CodeParent");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setCodecc(pCode);
            jieDianBeanIn.setCodeSub(code);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            PCBeanOut pcBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), PCBeanOut.class);
                            if (pcBeanOut == null) {
//                                subCodeDialog.dismiss();
                                return;
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (pcBeanOut.getErrcode() == 0 && pcBeanOut.getData() != null) {
                                        List<NoBillBeanOut.DataBean.BomResultBean.BomListBean> list = new ArrayList<>();
                                        for (int i = 0; i < pcBeanOut.getData().getBomList().size(); i++) {
                                            NoBillBeanOut.DataBean.BomResultBean.BomListBean datab = new NoBillBeanOut.DataBean.BomResultBean.BomListBean();
                                            datab.setProductName(pcBeanOut.getData().getBomList().get(i).getProductName());
                                            datab.setIsNeedScan(pcBeanOut.getData().getBomList().get(i).getIsNeedScan());
                                            datab.setScanState(pcBeanOut.getData().getBomList().get(i).getScanState());
                                            list.add(datab);
                                        }
                                        subCodeDialog.updateData(list);
                                    } else if (pcBeanOut.getErrcode() == 2) {
                                        showMsg(pcBeanOut.getErrmsg());
                                        subCodeDialog.dismiss();
                                    } else {
                                        showMsg(pcBeanOut.getErrmsg());
                                        voiceUtils.voiceWarn();
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }

    public void hm(String code, String code1) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            ScanfBeanIn scanfBeanIn = new ScanfBeanIn();
            scanfBeanIn.setAction("SY_UpdateCode_HuanMa");
            scanfBeanIn.setCid(SharedPreferencesManger.getCid());
            scanfBeanIn.setUserID(SharedPreferencesManger.getUid());
            scanfBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            scanfBeanIn.setCode(code);
            scanfBeanIn.setCodeHuanMa(code1);
            scanfBeanIn.setProcessID(dataBean.getProcessID());
            scanfBeanIn.setJieDianName(dataBean.getJieDianName());

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(scanfBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            BaseBeanOut baseBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), BaseBeanOut.class);
                            if (baseBeanOut == null) {
                                return;
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (baseBeanOut.getErrcode() == 0) {
                                        hmDialog.dismiss();
                                        showMsg("数码成功替换");
                                    } else {
                                        voiceUtils.voiceWarn();
                                        showMsg(baseBeanOut.getErrmsg());
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }

    public void fm(final String code) {
        try {
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            ScanfBeanIn scanfBeanIn = new ScanfBeanIn();
            scanfBeanIn.setAction("SY_GetCodeFuMa");
            scanfBeanIn.setCid(SharedPreferencesManger.getCid());
            scanfBeanIn.setUserID(SharedPreferencesManger.getUid());
            scanfBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            scanfBeanIn.setCode(code);
            scanfBeanIn.setProcessID(dataBean.getProcessID());
            scanfBeanIn.setJieDianName(dataBean.getJieDianName());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(scanfBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            FMBeanOut fmBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), FMBeanOut.class);
                            if (fmBeanOut == null) {
                                return;
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (fmBeanOut.getErrcode() == 0) {
                                        fmDialog.setList(fmBeanOut.getData());
                                    } else {
                                        fmDialog.dismiss();
                                        showMsg(fmBeanOut.getErrmsg());
                                        voiceUtils.voiceWarn();
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }

    public void fmscanf(String zcode, String code) {
        try {
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            ScanfBeanIn scanfBeanIn = new ScanfBeanIn();
            scanfBeanIn.setAction("SY_UpdateCode_FuMa");
            scanfBeanIn.setCid(SharedPreferencesManger.getCid());
            scanfBeanIn.setUserID(SharedPreferencesManger.getUid());
            scanfBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            scanfBeanIn.setCode(zcode);
            scanfBeanIn.setCodeFuMa(code);
            scanfBeanIn.setProcessID(dataBean.getProcessID());
            scanfBeanIn.setJieDianName(dataBean.getJieDianName());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(scanfBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            FMBeanOut fmBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), FMBeanOut.class);
                            if (fmBeanOut == null) {
                                return;
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (fmBeanOut.getErrcode() == 0) {
                                        fmDialog.setText(code);
                                        fmDialog.setList(fmBeanOut.getData());
                                        showMsg("副码绑定成功");
                                    } else {
                                        showMsg(fmBeanOut.getErrmsg());
                                        voiceUtils.voiceWarn();
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }
}
